//
//  JRADViewController.swift
//  JRADLaunchModule
//
//  Created by 京睿 on 2017/5/22.
//  Copyright © 2017年 JingRuiWangKe. All rights reserved.
//

import UIKit
import SnapKit

class JRADViewController: UIViewController {
    
    private typealias this = JRADViewController
    
    private lazy var manager: ADLaunchable = {
        return JRADLaunchManager.manager
    } ()
    
    private lazy var imageView: UIImageView = {
        let foo = UIImageView()
        foo.backgroundColor = UIColor.white
        foo.isUserInteractionEnabled = true
        if let url = UserDefaults.standard.object(forKey: loadingKey) as? String {
            foo.sd_setImage(with: URL.init(string: url))
        }
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(onTap(_:)))
        foo.addGestureRecognizer(tap)
        return foo
    } ()
    
    private lazy var cancelButton: UIButton = {
        let foo = UIButton.init(type: .custom)
        foo.setTitle("跳过(\(Int(this.maxCountdown)))", for: .normal)
        foo.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        foo.addTarget(self, action: #selector(onExit), for: .touchUpInside)
        foo.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        foo.layer.cornerRadius = 8
        foo.layer.masksToBounds = true
        return foo
    } ()
    
    private static var maxCountdown: TimeInterval = 0
    
    convenience init(by countdown: TimeInterval!) {
        self.init()
        guard let countdown = countdown else { return }
        this.maxCountdown = countdown
    }
    
    fileprivate var timer: Timer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(imageView)
        view.addSubview(cancelButton)
        
        imageView.snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
        
        cancelButton.snp.makeConstraints {
            $0.top.trailing.equalToSuperview().inset(20)
            $0.width.greaterThanOrEqualTo(55)
            $0.height.equalTo(20)
        }
        
        startCountDown()
    }
    
    private func startCountDown() {
        timer = Timer.JREvery(1.JRSeconds) { [weak self] in
            this.maxCountdown -= 1.JRSeconds
            self?.cancelButton.setTitle("跳过(\(Int(this.maxCountdown)))", for: .normal)
            if this.maxCountdown <= 0 {
                $0.invalidate()
                self?.onExit()
            }
        }
    }
    
    @objc private func onTap(_ sender: UITapGestureRecognizer) {
        manager.jump()
    }
    
    @objc private func onExit() {
        manager.exit()
    }
    
    deinit {
        print("ok")
    }
}
